/*
 * Copyright Hundsun Technologies Inc. All Rights Reserved.
 */

package mq

// register the Client driver
import (
	"fmt"

	"hundsun.com/hsl/hschain/common/types"

	"hundsun.com/hsl/hschain/common/config"
)

type mqClientCreate func(cfg *config.PluginConfig, mode string) (Client, error)

var regMqClient = make(map[string]mqClientCreate)

// Register 注册 Client driver
func Register(name string, create mqClientCreate) {
	if create == nil {
		panic("Client: Register driver is nil")
	}
	if _, dup := regMqClient[name]; dup {
		panic(fmt.Sprintf("Client: driver %s has Registered", name))
	}
	regMqClient[name] = create
}

// NewMq 根据mq的名称创建不同类型mq
func NewMq(cfg *config.PluginConfig, mode string) (Client, error) {
	creator, ok := regMqClient[cfg.Name]
	if !ok {
		fmt.Printf("NewMqClient: Register have not find %s driver", cfg.Name)
		return nil, types.ErrNotFound
	}
	c, err := creator(cfg, mode)
	if err != nil {
		return nil, err
	}
	return c, nil
}
